#include "bsp_init.h"

/*中断处理函数表*/
static sys_irq_handle irqTable[NUMBER_OF_INT_VECTORS];

/*记录中断嵌套数*/
static uint64_t irqNesting ;

/*初始化中断处理函数表*/
void system_irqtable_init(void){
    unsigned int i = 0;
    /*中断嵌套数计数初始化*/
    irqNesting = 0;
    for(i = 0 ; i<NUMBER_OF_INT_VECTORS ; i++){
        irqTable[i].irqHandler = default_irqhandler;
        irqTable[i].userParam = NULL;

    }
}

/*注册中断处理函数*/
/*  handler:处理具体外设中断时的中断服务函数
    userParam:传给处理具体外设中断时的中断服务函数的参数
*/
void system_register_irqhandler(IRQn_Type irq_ID, system_irq_handler_t handler, void *userParam){
    irqTable[irq_ID].irqHandler = handler;
    irqTable[irq_ID].userParam = userParam;
}

//IRQ中断处理函数，当触发IRQ中断时，会调用该函数
//gicciar:寄存器GICC_IAR的值，底十位存储着中断ID
void system_irqhandler(unsigned int gicciar){

    uint32_t irq_ID = gicciar & 0x3ff;

    /*检查中断ID是否小于160*/
    if(irq_ID >= NUMBER_OF_INT_VECTORS){
        return ;
    }

    /*根据中断号执行外部中断服务函数*/
    irqNesting++;
    irqTable[irq_ID].irqHandler(irq_ID , irqTable[irq_ID].userParam);
    irqNesting--;

}


/*中断初始化*/
void int_init(void){

    GIC_Init();
    system_irqtable_init();

    /*设置中断向量偏移值*/
    //已经在start.s中设置过，这里可设置可不设置。
    //__set_VBAR(0x87000000);

}

/*默认中断处理函数*/
void default_irqhandler(unsigned int gicciar, void *usrParam){
    while(1);
}
